package com.example.firstapp.adapter;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.firstapp.R;
import com.example.firstapp.entity.UserPreference;
import com.example.firstapp.entity.foodType;
import com.example.firstapp.entity.Domain.FoodType;

public class foodTypeAdapter extends ArrayAdapter<foodType> {
	int resourceID;
	ArrayList<foodType> items;
	Context context;
	int posRemove;
	ListView listFood;
	UserPreference userPref;
	float delta = 98;
	SharedPreferences sharedPref;
	public foodTypeAdapter(Context context, ListView listFood, int resourceID,
			ArrayList<foodType> items, UserPreference userPref, SharedPreferences sharedPref) {
		super(context, resourceID, items);
		this.resourceID = resourceID;
		this.items = items;
		this.context = context;
		this.listFood = listFood;
		this.userPref = userPref;
		this.sharedPref = sharedPref;
		
	}
	public int getPosRemove (){
		return posRemove;
	}
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		View row = convertView;

		if (row == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			row = inflater.inflate(resourceID, parent, false);
		}
		TextView foodType = (TextView) row.findViewById(R.id.textItemFood);
		ImageView foodImg = (ImageView) row.findViewById(R.id.imgFood);
		Button button = (Button) row.findViewById(R.id.removeButton);
		
		foodType.setText(items.get(position).type);
		foodImg.setImageResource(items.get(position).img);
		
		
		button.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				posRemove  = position;
				System.out.println("removed pos : " + posRemove);
				String item = items.get(position).type;
				items.remove(position);
				
//				userPref.getFoodtypes().remove(position);
				Set<String> foodTypesPref = sharedPref.getStringSet(context.getString(R.string.food_types_preference_saving), new HashSet<String>());
				Set<String> newFoodTypesPref = new HashSet<String> ();
				for (String type : foodTypesPref){
					if(!item.equals(type))
						newFoodTypesPref.add(type);					
				}
				SharedPreferences.Editor editor = sharedPref.edit();
				editor.putStringSet(context.getString(R.string.food_types_preference_saving), newFoodTypesPref);
				editor.commit();
				LayoutParams params2 = listFood.getLayoutParams();
				params2.height -= delta;
				notifyDataSetChanged();
			}
		});
		return row;
	}
}
